'use strict';

let fs=require('fs');
let path=require('path');
let router=require('koa-router')();

function searchControllers(){
    let files=fs.readdirSync(__dirname);

    let filterFiles=files.filter(fileName=>{
        return fileName.endsWith('.js')&&fileName!=='index.js'
    })
    return filterFiles;
}

function register(files){
    files.forEach(item=>{
        let fullPath=path.join(__dirname,item);
        let routerObj=require(fullPath);

        for(let item in routerObj){
            let type=routerObj[item][0]
            let fn=routerObj[item][1]

            if(type==='get'){
                router.get(item,fn)
            }else if(type==='post'){
                router.post(item,fn)
            }else if (type==='put'){
                router.put(item,fn)
            }else if(type==='delete'){
                router.delete(item,fn)
            }else{
                console.log('数据请求错误');
            }
        }
    })
}
module.exports=function(){
    let files=searchControllers();
    register(files);
    return router.routes();
}